'use strict';
var React = require('react'),
	DescTextarea = require('./descTextarea');

var ChoiceQuestion = React.createClass({
	getAnswer:function(){
		return {
			answer:this.state.answer.join(','),
			desc : this.state.desc
		};
	},
	getDefaultProps:function(){
		return {
			curValue:{answer:'',desc:''}
		};
	},
	componentDidUnMount:function(){
		this.state = null;
	},
	componentDidUpdate:function(prevProps,prevState){
		this._handleChecked();
	},
	componentDidMount:function(){
		this._handleChecked();
	},
	getInitialState:function(){
		return {
			answer:[],
			desc : ''
		};
	},
	_handleChecked:function(){
		this.state.answer = [];
		console.log(this.props.curValue);
		var self = this,
			tmp = !this.props.curValue.answer ? [] : this.props.curValue.answer.split(',');
		for(var i = 0 ; i < 4 ; i++){
			_.indexOf(tmp,i+"") == -1 ? self.refs['ref_'+i].checked = false : self.refs['ref_'+i].checked = true;
		}
		this.state.answer = _.compact(tmp);
		this.state.desc = !this.props.curValue.desc ? '' : this.props.curValue.desc;
		//this.refs.descRef.value = !this.props.curValue.desc ? '' : this.props.curValue.desc;
	},
	_handleDesc:function(desc){
		this.state.desc = desc;
		if(this.props._answer){
			this.props._answer({desc:desc});
		}
	},
	handleChange:function(e){
		if(this.props.type == 'radio'){
			this.state.answer[0] = this.refs['ref_'+e.target.value].value;
		}else{
			if(!e.target.checked){
				this.state.answer.splice(_.indexOf(this.state.answer,e.target.value),1);
			} else if(_.indexOf(this.state.answer,e.target.value) == -1){
				this.state.answer.push(e.target.value);
			}
		}
		if(this.props._answer){
			this.props._answer({answer:this.state.answer.join(',')});
		}
	},
	render:function(){
		console.log('ChoiceQuestion render ........');
		var self = this;
		var tmp = _.map(this.props.question.res,function(res,index){
			return <li className={self.props.type} key={index}>
						<label className={self.props.type}>
							<input
								type={self.props.type}
								ref = {'ref_'+index}
								value = {index}
								name = {self.props.type}
								onChange = {self.handleChange}
							/>
							{res}
						</label>
					</li>;
		});
		return (
			<div className="panel panel-success">
				<div className="panel-heading">
					<strong>第{this.props.question.index}题: {this.props.question.title}</strong>
				</div>
				<div className='panel-body'>
					<ul className="list-unstyled">
						{tmp}
					</ul>
				</div>
				<DescTextarea _answer={this._handleDesc} curValue={this.props.curValue.desc} />
			</div>
		);
	}
});

module.exports = ChoiceQuestion;